#coding=utf-8
'''
Created on 2017-6-13

@author: sandy
'''

import logging
import LogManager
import RemoteManager
import Utils,Const
import Pack as packet
import ManagerBuild
import zlib
import json
import RemoteManager
import imp
import hashlib

def cmdKeepAlive(manager,pkt):
    logging.debug("manager-->xxxx keepAlive")
    pass

def cmdLoginRet(manager,pkt):
    ecode = packet.unpack("H", pkt)
    if ecode != Const.ERR_OK:
        logging.info(u'Login Manager Failed ecode=%d', ecode)
    else:
        logging.info(u'Login Manager Sucess ecode=%d', ecode)
        RemoteManager.instance.onLoginRet()
    pass

def cmdRemoteCfg(manager,pkt):
    cfgname, cfg = packet.unpack("sS", pkt)
    cfgname = Utils.pstr2u(cfgname)
    logging.info(u'cmdRemoteCfg(), cfgname=%s', cfgname)
    cfg = zlib.decompress(cfg)
    jf = json.loads(cfg)
    RemoteManager.instance.onGotCfg(cfgname, jf)
    pass

#热更新
def cmdRemotePatch(manager,pkt):
    patchname, md5str ,content = packet.unpack("ssS", pkt)
    logging.debug(u"ManagerParse cmdRemotePatch patchname = %s",patchname)
    patchname = Utils.pstr2u(patchname)
    zclen = len(content)
    decontent = zlib.decompress(content)
    clen = len(decontent)
    logging.info(u"cmdRemotePatch() name=%s, zclen=%d clen=%d", patchname, zclen, clen)
    md5NewStr = hashlib.md5(decontent).hexdigest()
    if md5str == md5NewStr:
        try:
            mod = imp.new_module(patchname)
            exec decontent in globals(), mod.__dict__
            #sys.modules[patchname] = mod
            #mod.patch()
        except Exception:
            logging.exception(u"cmdRemotePatch() patch=%s", patchname)
    else:
        logging.info(u"ManagerParse cmdRemotePatch md5 not same")
    pass

def cmdLogLevel(manager,pkt):
    loglevel = packet.unpack("s", pkt)
    loglevel = Utils.pstr2u(loglevel)
    logging.info(u'cmdLogLevel(), level=%s', loglevel)
    LogManager.instance.setLogLevel(loglevel)
    
def cmdRemoteCfgFin(manager,pkt):
    RemoteManager.instance.recvConfFin()

__cmdTable = {
              Const.CMD_KEEP_ALIVE            : cmdKeepAlive,
              Const.CMD_MGR2XX_LOGIN_RET      : cmdLoginRet,
              Const.CMD_MGR2XX_REMOTE_CFG     : cmdRemoteCfg,
              Const.CMD_MGR2XX_REMOTE_CFG_FIN : cmdRemoteCfgFin,
              Const.CMD_MGR2XX_REMOTE_PATCH   : cmdRemotePatch,
              Const.CMD_MGR2XX_LOG_LEVEL      : cmdLogLevel
              
             }
def parse(manager,cmd,pkt):
    if cmd == Const.CMD_KEEP_ALIVE:
        return
    logging.debug(u"ManagerParse cmd = %d",cmd)
    func = __cmdTable.get(cmd)
    if not func :
        logging.debug(u"unknow cmd=%d" % cmd)
        return
    func(manager, pkt)